package com.valohyd.android_utils.tabs;

import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
 
/**
 * Implementation of {@link CompatTabListener} to handle tab change events. This
 * implementation instantiates the specified fragment class with no arguments
 * when its tab is selected.
 */
public class InstantiatingTabListener implements CompatTabListener {

    private final SherlockFragmentActivity          mActivity;
    private final Class<? extends SherlockFragment> mClass;

    /**
     * Constructor used each time a new tab is created.
     * 
     * @param activity
     *            The host Activity, used to instantiate the fragment
     * @param cls
     *            The class representing the fragment to instantiate
     */
    public InstantiatingTabListener(SherlockFragmentActivity activity, Class<? extends SherlockFragment> cls) {
        mActivity = activity;
        mClass = cls;
    }

    /* The following are each of the ActionBar.TabListener callbacks */
    public void onTabSelected(CompatTab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        SherlockFragment fragment = tab.getFragment();
        if (fragment == null) {
            // If not, instantiate and add it to the activity
            fragment = (SherlockFragment)SherlockFragment.instantiate(mActivity, mClass.getName());
            tab.setFragment(fragment);
            ft.add(android.R.id.tabcontent, fragment, tab.getTag());
        } else {
            // If it exists, simply attach it in order to show it
            //ft.attach(fragment);
            // si il existe, simplement l'afficher
            ft.show(fragment);
        }
    }

    public void onTabUnselected(CompatTab tab, FragmentTransaction ft) {
        SherlockFragment fragment = tab.getFragment();
        if (fragment != null) {
            // Detach the fragment, because another one is being attached
            //ft.detach(fragment);
            // cacher le fragment
            ft.hide(fragment);
        }
    }

    public void onTabReselected(CompatTab tab, FragmentTransaction ft) {
        // User selected the already selected tab. 
        // detach le fragment actuel
        /*Fragment fragment = tab.getFragment();
        if (fragment != null) {
            ft.detach(fragment);
        }
        // reload the fragment
        Fragment f = Fragment.instantiate(mActivity, mClass.getName());
        tab.setFragment(f);
        ft.add(android.R.id.tabcontent, f, tab.getTag());
        ft.attach(f);*/
    }
}